package com.pacs.common;

import com.pacs.entity.ExamEntity;
import com.pacs.entity.ExamItemsEntity;
import com.pacs.entity.ExamOrganEntity;
import com.pacs.entity.ExamSynRecEntity;
import com.pacs.mapping.*;
import com.pacs.vmapping.VExamItemMapper;
import com.pacs.vmapping.VExamMapper;
import com.pacs.vmapping.VExamOrganMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
public class ExamSynTask {
    @Resource private SysRegular sysRegular;
    @Resource private ExamSynRecMapper examSynRecMapper;
    @Resource private VExamMapper vExamMapper;
    @Resource private VExamItemMapper vExamItemMapper;
    @Resource private VExamOrganMapper vExamOrganMapper;
    @Resource private ExamMapper examMapper;
    @Resource private ExamItemMapper examItemMapper;
    @Resource private ExamOrganMapper examOrganMapper;
    @Resource private ExamPatientMapper examPatientMapper;

    @Scheduled(cron = "*/30 * * * * ?")
    @Transactional(transactionManager = "db1TransactionManager")
    public void execute() {
        //查询需要同步的检查
        List<ExamEntity> exams = vExamMapper.selectByIntervalDays(FunCommon.config.getIntervalDays(),FunCommon.config.getPatSource());
        System.out.println("同步申请单 ——————>" +exams.size()+"条");
        for(ExamEntity exam : exams) {
            ExamSynRecEntity examSynRec=new ExamSynRecEntity();
            exam.setExamId(sysRegular.getId("EXAM_ID"));
            exam.setExamStatus("30");
            exam.setFsyFlags(String.valueOf(FunCommon.config.getSynFlag()));
            examSynRec.setApplyId(exam.getApplyId());
            examSynRec.setSynDateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:mm")));
            examSynRec.setFlags("1");
            //病人信息
            String patId = sysRegular.getId("PAT_ID");
            exam.patient.setPatId(patId);
            exam.setPatId(patId);
            //检查项目
            List<ExamItemsEntity> items = vExamItemMapper.select(exam.getApplyId());
            if (items.size() != 0) {
                for (ExamItemsEntity item : items) {
                    item.setExamId(exam.getExamId());
                }
                examItemMapper.insert(items);
            }
            //检查部位
            List<ExamOrganEntity> organs = vExamOrganMapper.select(exam.getApplyId());
            if (organs.size() != 0) {
                for (ExamOrganEntity organ : organs) {
                    organ.setExamId(exam.getExamId());
                }
                examOrganMapper.insert(organs);
            }
            examPatientMapper.insert(exam.patient);
            examMapper.insert(exam);
            examSynRecMapper.insert(examSynRec);

        }

    }
}
